package com.dp.common.utils;

import cn.hutool.core.bean.BeanUtil;
import com.dp.common.domain.dto.UserDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.dp.common.constants.RedisConstants.LOGIN_USER_KEY;
import static com.dp.common.constants.RedisConstants.LOGIN_USER_TTL;

/**
 * 刷新登录状态
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 刷新token
     *
     * @param stringRedisTemplate
     */
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/*
        // 获取token
        String token = request.getHeader("authorization");
        if (token == null) {
            return true;
        }
        // 获取token中的用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
                // 不存在-拦截
        if (userMap.isEmpty()) {
            return false;
        }
*/
        // 从上游获取用户信息
        String userInfo = request.getHeader("user-info");
        if (userInfo == null || userInfo.isEmpty()) {
            return false;
        }
        // 反序列
        ObjectMapper objectMapper = new ObjectMapper();
        UserDTO userDTO = objectMapper.readValue(userInfo, UserDTO.class);
        // 存在-存入ThreadLocal
        UserHolder.saveUser(userDTO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        UserHolder.removeUser(); // 移除用户
    }
}
